import { useState, useEffect } from 'react'
import wordsData from './data/words.json'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'
import { speak } from './utils/speech';

function shuffle(array) {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}

function App() {
  const [cards, setCards] = useState([])
  const [selected, setSelected] = useState([])
  const [score, setScore] = useState(0)
  const [attempts, setAttempts] = useState(0)
  const [showCoins, setShowCoins] = useState(false)


  useEffect(() => {
    initializeGame()
  }, [])

  useEffect(() => {
    if (cards.every(c => c.isMatched)) {
      const interval = setInterval(() => {
        setShowCoins(s => !s)
      }, 3000)
      return () => clearInterval(interval)
    }
  }, [cards.every(c => c.isMatched)])

  const initializeGame = () => {
    const validPairs = wordsData.filter(word => 
      word?.word?.trim() && 
      word?.translation?.trim() &&
      word.word !== word.translation
    ).filter((v,i,a) => 
      a.findIndex(t => t.word === v.word && t.translation === v.translation) === i
    );

    // 按类型分组
    const groupedWords = {
      english: validPairs.filter(w => !w.type),
      math: validPairs.filter(w => w.type === 'math'),
      poem: validPairs.filter(w => w.type === 'poem')
    };

    // 根据当前模式选择词库
    const modes = ['english', 'math', 'poem'];
    const randomMode = modes[Math.floor(Math.random() * modes.length)];
    const selectedWords = groupedWords[randomMode];
    if (selectedWords.length < 8) {
      alert(`随机${randomMode}模式下有效单词对不足8组，请添加更多词条`);
      return;
    }

    // 生成严格配对的双语卡片
    const pairedWords = shuffle(validPairs)
      .slice(0,8)
      .flatMap(word => {
        if (word.type === 'math') {
          const questionCard = { ...word, langType: 'question', pairId: word.word };
          const answerCard = { ...word, langType: 'answer', pairId: word.word };
          return [questionCard, answerCard];
        } else if (word.type === 'poem') {
          const pairId = `poem_${word.word}_${word.translation}`;
          const upperVerse = { 
            ...word, 
            langType: 'upperVerse', 
            pairId: pairId, 
            originalText: word.word,
            translation: word.translation,
            isUpper: true 
          };
          const lowerVerse = { 
            ...word, 
            langType: 'lowerVerse', 
            pairId: pairId, 
            originalText: word.translation,
            translation: word.word,
            isUpper: false 
          };
          return [upperVerse, lowerVerse];
        } else {
          const enCard = { ...word, langType: 'en', pairId: word.word };
          const cnCard = { ...word, langType: 'cn', pairId: word.word };
          return [enCard, cnCard];
        }
      });

    const doubledWords = shuffle(pairedWords)
      .slice(0,16)
      .map((word, index) => ({
        id: index,
        ...word,
        isFlipped: false,
        isMatched: false
      }))
    setCards(doubledWords)
  }

  const handleCardClick = (id) => {
    if (selected.length === 2 || cards[id].isMatched) return

    const newCards = [...cards]
    newCards[id].isFlipped = true
    setCards(newCards)
    setSelected([...selected, id])

    if (selected.length === 1) {
      checkMatch(selected[0], id)
      setAttempts(a => a + 1)
    }
  }

  const checkMatch = (firstId, secondId) => {
    setTimeout(() => {
      // 严格的正反向匹配验证
const isTranslationMatch = cards[firstId].pairId === cards[secondId].pairId;

const isLangValid = 
  (cards[firstId].type === 'math' && 
  cards[secondId].type === 'math' &&
  cards[firstId].pairId === cards[secondId].pairId &&
  cards[firstId].langType !== cards[secondId].langType &&
  ((cards[firstId].langType === 'question' && cards[secondId].langType === 'answer') ||
   (cards[firstId].langType === 'answer' && cards[secondId].langType === 'question'))) ||
  (cards[firstId].type === 'poem' &&
  cards[secondId].type === 'poem' &&
  ((cards[firstId].langType === 'upperVerse' && cards[secondId].langType === 'lowerVerse' &&
    cards[firstId].originalText === cards[secondId].translation) ||
   (cards[firstId].langType === 'lowerVerse' && cards[secondId].langType === 'upperVerse' &&
    cards[firstId].originalText === cards[secondId].translation))) ||
  (!cards[firstId].type &&
  ((cards[firstId].langType === 'en' && cards[secondId].langType === 'cn') ||
   (cards[firstId].langType === 'cn' && cards[secondId].langType === 'en')));

const isMatch = isTranslationMatch && isLangValid;

      const newCards = cards.map(card => {
        if (card.id === firstId || card.id === secondId) {
          return {...card, isMatched: isMatch, isFlipped: isMatch}
        }
        return card
      })

      setCards(newCards)
      setSelected([])
      if (isMatch) {
  setScore(s => s + 10);
  speak(cards[firstId].word);
}
    }, 1000)
  }

  return (
    <div className="App">
      <div className="game-info">
        <h2>得分: {score}</h2>
        <p>尝试次数: {attempts}</p>

        <button onClick={initializeGame}>新游戏</button>
      </div>
      
      <div className="game-board">
        {cards.map(card => (
          <div 
            key={card.id}
            className={`card ${card.isFlipped ? 'flipped' : ''} ${card.isMatched ? 'matched' : ''} ${selected.includes(card.id) ? 'selected' : ''}`}
            onClick={() => handleCardClick(card.id)}
          >
            <div className="card-front">?</div>
            <div className="card-back">
              {card.type === 'math' 
  ? <div dangerouslySetInnerHTML={{
      __html: (card.langType === 'question' 
        ? card.word.replace(/×/g,'×').replace(/²/g,'²')
        : card.translation.replace(/×/g,'×').replace(/²/g,'²'))
    }} />
  : (card.langType === 'en' ? card.word : card.translation)}

            </div>
          </div>
        ))}
      </div>

      {cards.every(c => c.isMatched) && 
        <div className="win-message">
          <div className="coins-container">
            {showCoins && [...Array(20)].map((_, i) => (
              <div key={i} className="coin" style={{
                left: `${Math.random() * 100}%`,
                animationDelay: `${i * 0.2}s`,
                animationDuration: `${2 + Math.random() * 3}s`
              }} />
            ))}
          </div>
          <h2>恭喜获胜！</h2>
          <p>最终得分: {score}</p>
          <button 
            className="confirm-button"
            onClick={() => {
              setShowCoins(false);
              setCards(cards.map(c => ({...c, isMatched: false})));
              initializeGame();
            }}
          >
            确认
          </button>
        </div>}
    </div>
  )
}

export default App
